<template>
  <div ref="diffContainer"></div>
  <!-- <p>"diffContainer:"{{ diffContainer.value }}</p> -->
</template>

<script>
import { computed, ref, watch } from 'vue';
import { parse, html } from 'diff2html';
import 'diff2html/bundles/css/diff2html.min.css';

export default {
  name: 'DiffComponent',
  props: {
    diffs: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const diffContainer = ref(null);

    const renderDiff = (diffs) => {
      if (!diffContainer.value) return;

      const diffJson = parse(diffs);
      const diffHtml = html(diffJson, {
        drawFileList: true,
        matching: 'none',
        outputFormat: 'side-by-side', // 可以选择 'side-by-side'
        renderNothingWhenEmpty: false, // 内容相同没有改变不输出变化
        fileContentToggle: false, // 启用文件内容折叠功能
        highlight: true, // 启用代码高亮
        synchronisedScroll: true, // 启用同步滚动
      });

      diffContainer.value.innerHTML = diffHtml;

      initializeFileContentToggle(diffContainer.value);
    };

    const initializeFileContentToggle = (container) => {
      const fileHeaders = container.querySelectorAll('.d2h-file-header');
      fileHeaders.forEach(header => {
        header.addEventListener('click', () => {
          const fileContent = header.nextElementSibling;
          if (fileContent.style.display === 'none') {
            fileContent.style.display = 'block';
          } else {
            fileContent.style.display = 'none';
          }
        });
      });
    };

    watch(() => props.diffs, (newDiffs) => {
      console.log("变化了");
      renderDiff(newDiffs);
    }, { immediate: true });



    return {
      diffContainer
    };
  }
};
</script>

<style scoped>
/* Add any specific styles for the diff component here */
</style>
